<%@ page import="com.xtedu.examproject.util.RedisUtil" %>
<%@ page import="com.xtedu.examproject.entity.User" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: CBo
  Date: 2025/8/21
  Time: 10:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    // 优先从 showActive.jsp 传递的 roleId 获取，如果没有则从 Redis 获取
    Integer showActiveRoleId = (Integer) request.getAttribute("roleId");
    int roleId = 0;
    int infoId = 0;

    if (showActiveRoleId != null) {
        roleId = showActiveRoleId;
        // 从 session 中获取当前用户信息获取 infoId
        User sessionUser = (User) session.getAttribute("user");
        if (sessionUser != null) {
            infoId = sessionUser.getInfoId();
        }
    } else {
        // 回退到原来的 Redis 方式
        User currentUser = RedisUtil.getObject("user", User.class);
        roleId = currentUser != null ? currentUser.getRoleId() : 0;
        infoId = currentUser != null ? currentUser.getInfoId() : 0;
    }
    System.out.println("adduser.jsp中获取的roleId: " + roleId);
%>
<div>
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" id="addUserBtn" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
        添加用户
    </button>
    <!-- Modal -->
    <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1"
         aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="staticBackdropLabel">请输入信息</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form class="row g-3" id="addUserForm" method="post">
                        <div class="col-md-6">
                            <label for="selectRole">
                                <i class="bi bi-tag"></i>
                                选择角色</label>
                            <select id="selectRole" name="roleOption" class="form-control">
                                <option selected value="0">选择角色信息</option>
                                <!-- 通过JavaScript动态加载角色选项 -->
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="selectUser">
                                <i class="bi bi-person-check"></i>
                                选择添加用户</label>
                            <select id="selectUser" name="userOption" class="form-control">
                                <option selected value="0">选择用户信息</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="inputUserName">
                                <i class="bi bi-card-checklist"></i>
                                用户名</label>
                            <input type="text" name="username" class="form-control" id="inputUserName" readonly>
                        </div>
                        <div class="col-md-6">
                            <label for="inputPassword">
                                <i class="bi bi-lock"></i>
                                初始密码</label>
                            <input type="text" name="initialPwd" value="12345" class="form-control" id="inputPassword"
                                   readonly>
                        </div>
                        <div class="col-12" style="text-align: center;">
                            <button type="submit" id="submit" class="btn btn-primary"><i class="bi bi-check2"></i>确定
                            </button>
                            <button type="reset" id="reset" class="btn btn-danger"><i class="bi bi-arrow-clockwise"></i>重置
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(window).ready(function () {
        //选择角色信息下拉列表
        const selectRole = document.querySelector("#selectRole");
        //选择用户信息下拉列表
        const selectUser = document.querySelector("#selectUser");
        //用户名输入框 只读 值为选择的用户的phone
        const inputUsername = document.querySelector("#inputUserName");
        // 密码输入框
        const inputPassword = document.querySelector("#inputPassword");
        // 添加用户表单
        const addUserForm = document.querySelector("#addUserForm");
        // 表单重置按钮
        const $addFormResetBtn = $("#addUserForm #reset");
        //获取的用户信息
        let users = [];
        //当前登录用户角色id
        let loginRoleId = <%= roleId %>;
        let loginInfoId = <%= infoId %>;

        // 点击添加按钮发送请求
        $('#staticBackdrop').on('show.bs.modal', function () {
            $.get("${pageContext.request.contextPath}/usermanage/addUser", null, null, "json")
                .done(function(result) {
                    console.log("请求成功:", result);

                    // 处理业务逻辑
                    selectRole.innerHTML = `<option selected value="0">选择角色信息</option>`;
                    if (result && result.code === 200) {
                        if (result.data && Array.isArray(result.data)) {
                            result.data.forEach(role => {
                                const option = document.createElement('option');
                                option.value = role.id;
                                option.innerHTML = role.roleName;
                                selectRole.appendChild(option);
                            });
                        }
                    } else {
                        console.error("加载失败:", result ? result.message : "无响应数据");
                        alert("加载失败: " + (result ? result.message : "无响应数据"));
                    }
                })
                .fail(function(xhr, status, error) {
                    console.error("请求失败:");
                    console.error("状态:", status);
                    console.error("错误:", error);
                    console.error("响应文本:", xhr.responseText);
                    alert("请求失败: " + error);
                });
        });



        //获取老师所在班级学生非用户信息
        const getStuMethod = function () {
            $.ajax({
                type: "GET",
                url: "${pageContext.request.contextPath}/usermanage/showUser",
                data: {
                    selectedRoleId: "4"
                },
                dataType: "json",
                success: function (data) {
                    if (data.code === 200) {
                        users = data.data;
                        selectUser.innerHTML = '<option selected value="0">选择用户信息</option>';
                        users.forEach(user => {
                            const option = document.createElement('option');
                            option.value = user.id;
                            option.textContent = user.name;
                            selectUser.appendChild(option);
                        });
                    } else {
                        console.error('获取数据失败:', data.message);
                    }
                },
                error: function (xhr, status, error) {
                    console.error('请求失败: ' + error);
                }
            });
        }

        //获取所有非用户老师信息
        const getTeaMethod = function () {
            $.ajax({
                type: "GET",
                url: "${pageContext.request.contextPath}/usermanage/showUser",
                data: {
                    selectedRoleId: "1"
                },
                dataType: "json",
                success: function (data) {
                    console.log("请求成功:", data);
                    // 注意：这里 data 已经是解析后的对象，不需要再 JSON.parse
                    if (data.code === 200) {
                        users = data.data;
                        // 清空现有选项
                        selectUser.innerHTML = '<option selected value="0">选择用户信息</option>';
                        users.forEach(user => {
                            const option = document.createElement('option');
                            option.value = user.id;
                            option.textContent = user.name;
                            selectUser.appendChild(option);
                        });
                    } else {
                        console.error('获取数据失败:', data.message);
                    }
                },
                error: function (xhr, status, error) {
                    console.error('请求失败: ' + error);
                }
            });
        }

        //获取所有非用户学生信息
        const getAllStuMethod = function () {
            $.ajax({
                type: "GET",
                url: "${pageContext.request.contextPath}/usermanage/showUser",
                data: {
                    selectedRoleId: "4"
                },
                dataType: "json",
                success: function (data) {
                    if (data.code === 200) {
                        users = data.data;
                        selectUser.innerHTML = '<option selected value="0">选择用户信息</option>';
                        users.forEach(user => {
                            const option = document.createElement('option');
                            option.value = user.id;
                            option.textContent = user.name;
                            selectUser.appendChild(option);
                        });
                    } else {
                        console.error('获取数据失败:', data.message);
                    }
                },
                error: function (xhr, status, error) {
                    console.error('请求失败: ' + error);
                }
            });
        }

        //选择角色信息下拉列表
        selectRole.addEventListener('change', function () {
            // 重置用户名字段
            inputUsername.value = "";

            const selectedValue = this.value;

            //未选择角色
            if (selectedValue === "0") {
                console.log("未选择角色");
                // 重置动态加载的角色信息
                selectUser.innerHTML = `<option selected value="0">请先选择角色信息</option>`;
                // 重置用户名
                inputUsername.value = null;
                return;
            }

            // 发送AJAX请求获取对应角色的用户列表
            $.ajax({
                type: "GET",
                url: "${pageContext.request.contextPath}/usermanage/showUser",
                data: {
                    selectedRoleId: selectedValue
                },
                dataType: "json",
                success: function (data) {
                    if (data.code === 200) {
                        users = data.data;
                        // 清空并重新填充用户选择列表
                        selectUser.innerHTML = '<option selected value="0">选择用户信息</option>';
                        users.forEach((user, index) => {
                            const option = document.createElement("option");
                            option.value = user.id;  // 使用实际的用户ID而不是索引
                            option.innerHTML = user.name;
                            selectUser.appendChild(option);
                        });
                    } else {
                        alert("加载失败: " + data.message);
                        // 不建议直接跳转页面，可以考虑其他提示方式
                    }
                },
                error: function (xhr, status, error) {
                    console.error('请求失败:', error);
                    alert("加载失败: " + error);
                }
            });

            const selectedOption = this.options[this.selectedIndex];
            //未选择角色
            if (selectedOption.value === "0") {
                console.log("未选择角色");
                // 重置动态加载的角色信息
                selectUser.innerHTML = `<option selected value="0">请先选择角色信息</option>`;
                // 重置用户名
                inputUsername.value = null;
            }
            //选择学生角色
            if (selectedOption.value === "4") {
                //当前登录角色为老师
                if (loginRoleId === 1) {
                    getStuMethod();
                    //管理员
                } else
                    getAllStuMethod();
            }
            //选择老师角色
            if (selectedOption.value === "1") {
                getTeaMethod();
            }
        });

        //选择用户信息下拉列表
        selectUser.addEventListener('change', function () {
            console.log("选择用户信息下拉列表");
            //未选择用户
            if (this.selectedIndex === 0) {
                inputUsername.value = "";
                return;
            }
            //已选择用户phone填入用户名输入框
            // 修复：正确获取用户对象并提取phone字段
            const selectedIndex = this.selectedIndex - 1;
            if (users && users[selectedIndex] && users[selectedIndex].phone) {
                inputUsername.value = users[selectedIndex].phone;
            } else {
                inputUsername.value = "";
            }
        })

        // 表单提交事件
        addUserForm.addEventListener('submit', function (e) {
            e.preventDefault();
            $.post(
                "${pageContext.request.contextPath}/usermanage/add",
                {
                    username: inputUsername.value,
                    password: inputPassword.value,
                    roleOption: selectRole.value,
                    userOption: selectUser.value
                }
            ).then(result => {
                const resultObj = JSON.parse(result);
                if (resultObj.code === 200) {
                    alert(resultObj.message);
                    window.location.href = "${pageContext.request.contextPath}/usermanage";
                } else {
                    alert(resultObj.message);
                }
            }).catch(error => {
                alert(error);
            })
        });

        $addFormResetBtn.click(() => {
            // 重置动态加载的下拉框
            selectRole.value = 0;

            // 重置动态加载的角色信息
                selectUser.innerHTML = `<option selected value="0">请先选择角色信息</option>`;

            // 重置用户名字段
            inputUsername.value = "";

            // 确保密码字段恢复默认值
            inputPassword.value = "12345";
        });
    })
</script>




